package com.masterrabbit.gmh.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.masterrabbit.common.core.constant.SecurityConstants;
import com.masterrabbit.common.core.web.domain.AjaxResult;
import com.masterrabbit.gmh.domain.EmergencyRescueRecords;

import com.masterrabbit.gmh.domain.Merchants;
import com.masterrabbit.gmh.mapper.EmergencyRescueRecordsMapper;
import com.masterrabbit.gmh.service.EmergencyRescueRecordsService;


import com.masterrabbit.gmh.service.MerchantsService;
import com.masterrabbit.mcslf.api.RemoteMcslfService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.geo.*;


import org.springframework.data.geo.Point;

import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.web.bind.annotation.*;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/emergencyRescueRecords")
public class EmergencyRescueRecordsController {

    @Autowired
    private EmergencyRescueRecordsService service;
    @Autowired
    private MerchantsService merchantsService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;




    //生成UUID
    public String getUUID() {
        String uuidStr = UUID.randomUUID().toString();
        // 去除连字符（生成32位字符串）
        String compactUUID = uuidStr.replace("-", "");
        System.out.println("无连字符UUID: " + compactUUID);
        return compactUUID;
    }


    @PostMapping("/insert")
    public boolean insertRecord(@RequestBody EmergencyRescueRecords record) {
        System.out.println(record);
        //生成UUID
        String uuid = getUUID();
        record.setRescueNumber(uuid);

        rabbitTemplate.convertAndSend("aidexchange", "", uuid);
        //存入数据库
        boolean save = service.save(record);

        return save;

    }



    //查看历史记录 通过id查找信息
    @GetMapping("/getUserInfo")
    public List<EmergencyRescueRecords> getUserInfo(Integer userId) {

        Wrapper<EmergencyRescueRecords> wrapper = new QueryWrapper<EmergencyRescueRecords>()
                .eq("user_id", userId);

        List<EmergencyRescueRecords> emergencyRescueRecords = service.list(wrapper);

        return emergencyRescueRecords;

    }

    // 将商家信息存储到Redis
    @PostMapping("/addShopToRedis")
    public void addShopToRedis(Long merchantId, Double longitude, Double latitude) {
        redisTemplate.opsForGeo().add("shops", new Point(longitude, latitude), merchantId.toString());
    }


    //查找附近商家
    @GetMapping("/getNearbyBusiness")
    public List<Merchants> queryNearShops(double longitude, double latitude, double radius) {


        //设置查询参数
        GeoReference fromCoordinate=GeoReference.fromCoordinate(longitude,latitude);
        Distance distance=new Distance(radius,RedisGeoCommands.DistanceUnit.METERS);
        //执行查询
        GeoResults<RedisGeoCommands.GeoLocation<String>> results=redisTemplate.opsForGeo().search(
                "shops",
                fromCoordinate,
                distance,
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance()
        );
        //解析结果
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content=results.getContent();
        List<Merchants> merchants=new ArrayList<>();
        for (GeoResult<RedisGeoCommands.GeoLocation<String>> result : content){
            String merchantsIdStr=result.getContent().getName();
           Integer merchantId=Integer.valueOf(merchantsIdStr);
         List<Merchants> merchant= merchantsService.getMerchantsByMerchantId(merchantId);

            if (merchant != null) {
                // 设置距离信息到商家对象中
                for (Merchants merchant1 : merchant) {
                    merchant1.setDistance((double)Math.round(result.getDistance().getValue()));
                    //将商家图片加入到商家对象中
                    List<String> strings = merchantsService.selectByProductId(merchant1.getBusinessLicenseImageId());
                    merchant1.setStorefrontImageUrl(strings);
                    merchants.add(merchant1);
                }
            }
        }

      return merchants;



    }

}